import { Modal, NavBar, Image as MyImage } from "antd-mobile";
import { useEffect, useRef, useState } from "react";
import { useLocation, useNavigate } from "react-router-dom";
import $fetch from "../../utils/app/$fetch";
import $reducer from "../../utils/app/$reducer";
import SelectPopup from "./component/SelectPopup";
import { ReactComponent as QueueIcon } from '../../asset/imgs/queue.svg';
import { ReactComponent as WaitIcon } from '../../asset/imgs/wait.svg';
import { ReactComponent as TimeIcon } from '../../asset/imgs/time.svg';
import "./style.scss";

const iconColor = getComputedStyle(document.documentElement)
  .getPropertyValue('--logoColor')
  .trim();

const TypeEnum: any = {
  zhibo: "特典会",
  tedian: "特典会",
  yanchu: "演出",
};
// 0表示当前正在排队，前方人数为0，展示取消排队按钮；null表示当前并没有开始排队，展示开始排队按钮

export default function Queue() {
  const location: any = useLocation();
  const { eventId, eventType } = location?.state;
  const navigate = useNavigate();
  const intervalRefs: any = useRef(null);
  let closeQueueModal: any;

  const initState: any = {
    schduleList: [],
    showSelect: false,
    commonCoupon: 0,
    specificCoupon: 0,
    memberName: "",
    memberId: "",
  };

  const [state, dispatch] = $reducer({ ...initState });

  useEffect(() => {
    initPage();
    querySchedule();
    return () => {
      clearInterval(intervalRefs.current);
    };
  }, []);

  const initPage = async () => {
    const res = await $fetch(`/line/list/${eventId}`);
    dispatch({ schduleList: res });
  };

  useEffect(() => {
    if (state?.schduleList?.length > 0) {
      state?.schduleList.forEach((item: any) => {
        const img: any = new Image();
        img.src = item?.memberFormulPhoto;
      });
    }
  }, [state?.schduleList]);

  const querySchedule = () => {
    intervalRefs.current = setInterval(async () => {
      const res = await $fetch(`/line/list/${eventId}`, {}, { loading: false });
      dispatch({ schduleList: res });
    }, 10000);
  };

  const openModal = (memberId: any) => {
    closeQueueModal = Modal.show({
      content: "当前您是第一位，是否取消排队？",
      actions: [
        {
          key: "ok",
          text: "是",
          primary: true,
          onClick: async () => {
            await $fetch(
              `line/cancelLine/${memberId}?eventId=${eventId}`,
              {},
              { method: "post", noGroupId: "no" }
            );
            closeQueueModal();
            initPage();
          },
        },
        { key: "cancel", text: "否", onClick: () => closeQueueModal() },
      ],
    }).close;
  };

  const handleQueue = async (item: any) => {
    if (item?.frontNum === 0) {
      openModal(item?.memberId);
    }
    if (item?.frontNum === null) {
      if (eventType === "2") {
        // 电切排队，弹窗，输入数量
        dispatch({
          showSelect: true,
          memberName: item?.memberName,
          memberId: item?.memberId,
        });
      } else {
        // 特典排队
        await $fetch(
          `line/startLine/${item?.memberId}?eventId=${eventId}`,
          {},
          { method: "post", noGroupId: "no" }
        );
        initPage();
        return;
      }
    }
    if (item?.frontNum >= 1) {
      // 取消排队
      await $fetch(
        `line/cancelLine/${item?.memberId}?eventId=${eventId}`,
        {},
        { method: "post", noGroupId: "no" }
      );
      initPage();
      return;
    }
  };

  const onClose = (reload = false) => {
    dispatch({ showSelect: false, memberId: "", memberName: "" });
    if (reload) {
      initPage();
    }
  };

  const back = () => {
    // window.history.go(-1);
    navigate("/home", { state: { current: "activity" } });
  };

  return (
    <div className="container_queue_list">
      <NavBar
        style={{
          "--border-bottom": "1px #eee solid",
        }}
        onBack={() => back()}
      >
        排队详情
      </NavBar>
      <ul className="that_queue_list">
        {state?.schduleList.map((item: any, index: any) => {
          return (
            <li key={index}>
              <div className="img_wraper">
                <MyImage
                  src={item?.memberFormulPhoto}
                  fit="cover"
                  width="4rem"
                  height="4rem"
                  lazy={true}
                />
              </div>
              <div className="item_content_wraper">
                <div className="name">{item?.memberName}</div>
                <div className="center">
                  <div className="queue">
                    <div>
                      <QueueIcon width={50} height={50} fill={iconColor}/>
                      <span>排队人数：</span>

                    </div>
                    <span>{item?.lineNum || 0}人</span>
                  </div>
                  {item?.frontNum > 0 && (
                    <>
                      <div className="wait">
                        <div>
                          <WaitIcon width={50} height={50} fill={iconColor}/>
                          <span>前方人数：</span>
                        </div>
                        <span>{item?.frontNum}人</span>
                      </div>
                      {/* 电切会才展示时间 */}
                      {eventType === "2" && (
                        <div className="time">
                          <div>
                          <TimeIcon width={50} height={50} fill={iconColor}/>
                          <span>等待时间：</span>
                        </div>
                          <span>{Math.ceil(item?.waitingTime / 60)}分钟</span>
                        </div>
                      )}
                    </>
                  )}
                </div>
                <div className="click_queue" onClick={() => handleQueue(item)}>
                
                    {item?.frontNum === 0
                      ? <span className="cancel">取消排队</span>
                      : item?.frontNum == null
                      ? <span className="begin">开始排队</span>
                      : <span className="cancel">取消排队</span>}
                    {/* {(item?.frontNum == 0 ||  item?.frontNum == null) ? "开始排队" : "取消排队"} */}
                </div>
              </div>
            </li>
          );
        })}
      </ul>
      {state?.showSelect && (
        <SelectPopup
          memberName={state?.memberName}
          memberId={state?.memberId}
          onClose={onClose}
          eventId={eventId}
        />
      )}
    </div>
  );
}
